<?php
/**
*  GUI input form for person registration methods.
*
* Dependencies:
* assumes the following files are in the given path
* /include/care_api_classes/class_person.php
* /include/care_api_classes/class_paginator.php
* /include/care_api_classes/class_globalconfig.php
* /include/inc_date_format_functions.php
*  Note this class should be instantiated only after a "$db" adodb  connector object  has been established by an adodb instance
*/



$thisfile = basename($_SERVER['PHP_SELF']);

class GuiInputPerson {

	# Language tables
	var $langfiles= array('emr.php', 'person.php', 'date_time.php', 'aufnahme.php');

	# Default path for fotos. Make sure that this directory exists!
	var $default_photo_path='fotos/registration';

	# Filename of file running this gui
	var $thisfile = '';

	# PID number
	var $pid=0;
	
	# Toggler var
	var $toggle=0;

	# Color of error text
	var $error_fontcolor='#ff0000';

	# Text block above form
	var $pretext='';
	# Text block below the form
	var $posttext='';
	
	# filename for displaying the data after saving
	var $displayfile='';
	
	# smarty template
	var $smarty;
	
	# Flag for output or returning form data
	var $bReturnOnly = FALSE;

	/**
	* Constructor
	*/
	function GuiInputPerson($filename = ''){
		global $thisfile, $root_path;
		if(empty($filename)) $this->thisfile = $thisfile;
			else $this->thisfile = $filename;
	}
	/**
	* Sets the PID number
	*/
	function setPID($pid=0){
		if(!empty($pid)) $this->pid = $pid;
	}
	/**
	* Sets the PID number
	*/
	function setDisplayFile($fn=''){
		if(!empty($fn)) $this->displayfile = $fn;
	}
	/**
	* Create a row of input element in the form
	*/
	function createTR($error_handler, $input_name, $ld_text, $input_val, $colspan = 1, $input_size = 35,$red=FALSE){
		
		global $db, $sid, $lang, $root_path, $pid, $insurance_show, $user_id, $mode, $dbtype, $breakfile, $cfg,
		$update, $photo_filename, $_POST,  $_FILES, $_SESSION;

		extract($_POST);
		# Load the language tables
		$lang_tables =$this->langfiles;
		include($root_path.'include/inc_load_lang_tables.php');
		
		# Load the other hospitals array
		include_once($root_path.'global_conf/other_hospitals.php');

		include_once($root_path.'include/inc_date_format_functions.php');
		include_once($root_path.'include/care_api_classes/class_insurance.php');
		include_once($root_path.'include/care_api_classes/class_person.php');
                include_once($root_path.'include/care_api_classes/class_interconsulta.php');
		ob_start();
			if ($error_handler || $red) $sBuffer="<font color=\"$this->error_fontcolor\">$ld_text</font>";
				else $sBuffer=$ld_text;
			$this->smarty->assign('sItem',$sBuffer);
			$this->smarty->assign('sColSpan2',"colspan=$colspan");

                        if (strcmp($input_name, "nat_id_nr") == 0)
			  {
			    
			    $this->smarty->assign('sInput','<select name="'.$input_name.'_tipo" onChange="setNacionalidad();"><option value="V" ' . ((substr($input_val, 0, 1) == "V")?("selected"):("")) . '>V</option><option value="E" ' . ((substr($input_val, 0, 1) == "E")?("selected"):("")) . '>E</option><option value="N" ' . ((substr($input_val, 0, 1) == "N")?("selected"):("")) . '>'.$LDNoCedula.'</option></select><input name="'.$input_name.'" id="'.$input_name.'" type="text" size="'.$input_size.'" value="'.substr($input_val,1).'" onblur="setNacionalidad(); makePOSTRequest(\'ajax-person.php\');"' . ((substr($input_val, 0, 1) == "N")?("disabled"):("")) . '>');
			    
			  }
                        else if ((strcmp($input_name, "phone_1_nr") == 0) || (strcmp($input_name, "cellphone_1_nr") == 0))
			  {
			    $this->smarty->assign('sInput', '<input id="'.$input_name.'_cod" name="'.$input_name.'_cod" type="text" size="4" maxlength="4" value="'.substr($input_val,0,4).'"><input id="'.$input_name.'" name="'.$input_name.'" type="text" size="7" maxlength="7" value="'.substr($input_val,4).'">');
			  }
                        else
			  {
			    
			    $this->smarty->assign('sInput','<input name="'.$input_name.'" type="text" size="'.$input_size.'" value="'.$input_val.'" maxlength="25">');
			  }
			
			
			

			$this->smarty->display('registration_admission/reg_row.tpl');
			$sBuffer = ob_get_contents();
		ob_end_clean();

		//$this->toggle=!$this->toggle;

		return $sBuffer;
	}

	/**
	* Displays the GUI input form
	*/
	function display(){
		global $db, $sid, $lang, $root_path, $pid, $insurance_show, $user_id, $mode, $dbtype, $breakfile, $cfg,
		$update, $photo_filename, $_POST,  $_FILES, $_SESSION;

		extract($_POST);
		# Load the language tables
		$lang_tables =$this->langfiles;
		include($root_path.'include/inc_load_lang_tables.php');
		
		# Load the other hospitals array
		include_once($root_path.'global_conf/other_hospitals.php');

		include_once($root_path.'include/inc_date_format_functions.php');
		include_once($root_path.'include/care_api_classes/class_insurance.php');
		include_once($root_path.'include/care_api_classes/class_person.php');
                include_once($root_path.'include/care_api_classes/class_interconsulta.php');


		//system("logger -t xxx $phone_1_nr_cod $phone_1_nr");
		$phone_1_nr = $phone_1_nr_cod . $phone_1_nr;
		$cellphone_1_nr = $cellphone_1_nr_cod . $cellphone_1_nr;
		$_POST['phone_1_nr'] = $phone_1_nr;
		$_POST['cellphone_1_nr'] = $cellphone_1_nr;
		//system("logger -t xxx $phone_1_nr");
		
		//$db->debug=true;

		# Create the new person object
		$person_obj=& new Person($pid);

		# Create a new person insurance object
		$pinsure_obj=& new PersonInsurance($pid);

		if(!isset($insurance_show)) $insurance_show=TRUE;

		$newdata=1;

		$error=0;
		$dbtable='care_person';

		if(!isset($photo_filename)||empty($photo_filename)) $photo_filename='nopic';
		# Assume first that image is not uploaded
		$valid_image=FALSE;

		//* Get the global config for person's registration form*/
		include_once($root_path.'include/care_api_classes/class_globalconfig.php');
		$glob_obj=new GlobalConfig($GLOBAL_CONFIG);
		$glob_obj->getConfig('person_%');
		
		# Check whether config foto path exists, else use default path
		$photo_path = (is_dir($root_path.$GLOBAL_CONFIG['person_foto_path'])) ? $GLOBAL_CONFIG['person_foto_path'] : $this->default_photo_path;

		if (($mode=='save') || ($mode=='forcesave')) {

// 	echo "<pre>";
// 	var_dump($_POST);
// 	echo "</pre>";

			# If saving is not forced, validate important elements
			if($mode!='forcesave') {
				# clean and check input data variables
				if(trim($encoder)=='') $encoder=$aufnahme_user;
				if (trim($name_last)=='') { $errornamelast=1; $error++;}
				if(trim($name_first)=='') { $errornamefirst=1; $error++; }
				if (trim($date_birth)=='') { $errordatebirth=1; $error++;}
				if ($sex=='') { $errorsex=1; $error++;}
				if (trim($nat_id_nr)=='') { if($nat_id_nr_tipo != 'N') {$errorcedula=1; $error++;}}
				if (trim($citizenship)=='') { $errorcitizenship=1; $error++;}
				if ($civil_status=='') { $errorcivilstatus=1; $error++;}
				if ($sso=='') { $errorsso=1; $error++;}
				if (trim($addr_entity)=='') { $erroraddrentity=1; $error++;}
				if (trim($addr_town)=='') { $erroraddrtown=1; $error++;}
				if (trim($addr_citytown_name)=='') { $erroraddrcitytownname=1; $error++;}
				if (trim($addr_sector)=='') { $errorsector=1; $error++;}
				/*
				echo "ERROR namelast: " . $errornamelast;
echo "ERROR namelast: " . $errornamelast;
echo "ERROR namefirst: " . $errornamefirst;
echo "ERROR datebirth " . $errordatebirth;
echo "ERROR sex: " . $errorsex;
echo "ERROR cedula: " . $errorcedula;
echo "ERROR citizenship: " . $errorcitizenship;
echo "ERROR civilstatus: " . $errorcivilstatus;
echo "ERROR sso: " . $errorsso;
echo "ERROR addrentity: " . $errorentity;
echo "ERROR addrtown: " . $erroraddrtown;
echo "ERROR addrcitytownname: " . $erroraddrcitytownname;
echo "ERROR sector: " . $errorsector;
				*/
			}


			# If the validation produced no error, save the data
			if(!$error) {
				# Save the old filename for testing
				$old_fn=$photo_filename;

				# Create image object
				include_once($root_path.'include/care_api_classes/class_image.php');
				$img_obj=& new Image;

				# Check the uploaded image file if exists and valid
				if($img_obj->isValidUploadedImage($_FILES['photo_filename'])){
					$valid_image=TRUE;
					# Get the file extension
					$picext=$img_obj->UploadedImageMimeType();
				}
				
				if(($update)) {
                                  
				  /*$sql.="UPDATE $dbtable SET
							 title='$title',
							 name_last='$name_last',
							 name_first='$name_first',
							 name_2='$name_2',
							 name_middle='$name_middle',
							 date_birth='".formatDate2STD($date_birth,$date_format)."',
							 blood_group='".trim($blood_group . $rh)."',
							 sex='$sex',
							 addr_str='$addr_str',
							 addr_str_nr='$addr_str_nr',
							 addr_zip='$addr_zip',
							 addr_citytown_name='$addr_citytown_name',
							 addr_citytown_nr='$addr_citytown_nr',
							 phone_1_nr='$phone_1_nr',
							 phone_2_nr='$phone_2_nr',
							 cellphone_1_nr='$cellphone_1_nr',
							 cellphone_2_nr='$cellphone_2_nr',
							 fax='$fax',
							 email='$email',
							 civil_status='$civil_status',
							 citizenship='$citizenship',
							 nat_id_nr='$nat_id_nr_tipo$nat_id_nr',
							 religion='$religion',
							 ethnic_orig='$ethnic_orig',
							 addr_locality='$addr_locality',
							 birth_country='$birth_country',
							 birth_entity='$birth_entity',
							 birth_town='$birth_town',
							 birth_city='$birth_city',
							 illiterate='$illiterate',
							 educational_level='$educational_level',
							 educational_plan='$educational_plan',
							 years_approved='$years_approved',
							 profession='$profession',
							 occupation='$occupation',
							 sso='$sso',
							 addr_entity='$addr_entity',
							 addr_town='$addr_town',
							 addr_sector='$addr_sector',
							 addr_house='$addr_house',
							 addr_floor='$addr_floor',
							 addr_reference='$addr_reference',
							 addr_time='$addr_time',
							 name_mother='$name_mother',
							 name_father='$name_father',
							 date_update='".date('Y-m-d H:i:s')."',";*/

                                        $values=array(array(),array('title'=>$title,
							 'name_last'=>$name_last,
							 'name_first'=>$name_first,
							 'name_2'=>$name_2,
							 'name_middle'=>$name_middle,
							 'date_birth'=>"".formatDate2STD($date_birth,$date_format)."",
							 'blood_group'=>"".trim($blood_group . $rh)."",
							 'sex'=>$sex,
							 'addr_str'=>$addr_str,
							 'addr_str_nr'=>$addr_str_nr,
							 'addr_zip'=>$addr_zip,
							 'addr_citytown_name'=>$addr_citytown_name,
							 'addr_citytown_nr'=>$addr_citytown_nr,
							 'phone_1_nr'=>$phone_1_nr,
							 'phone_2_nr'=>$phone_2_nr,
							 'cellphone_1_nr'=>$cellphone_1_nr,
							 'cellphone_2_nr'=>$cellphone_2_nr,
							 'fax'=>$fax,
							 'email'=>$email,
							 'civil_status'=>$civil_status,
							 'citizenship'=>$citizenship,
							 'nat_id_nr'=>''.$nat_id_nr_tipo.''.''.$nat_id_nr.'',
							 'religion'=>$religion,
							 'ethnic_orig'=>$ethnic_orig,
							 'addr_locality'=>$addr_locality,
							 'birth_country'=>$birth_country,
							 'birth_entity'=>$birth_entity,
							 'birth_town'=>$birth_town,
							 'birth_city'=>$birth_city,
							 'illiterate'=>$illiterate,
							 'educational_level'=>$educational_level,
							 'educational_plan'=>$educational_plan,
							 'years_approved'=>$years_approved,
							 'profession'=>$profession,
							 'occupation'=>$occupation,
							 'sso'=>$sso,
							 'addr_entity'=>$addr_entity,
							 'addr_town'=>$addr_town,
							 'addr_sector'=>$addr_sector,
							 'addr_house'=>$addr_house,
							 'addr_floor'=>$addr_floor,
							 'addr_reference'=>$addr_reference,
							 'addr_time'=>$addr_time,
							 'name_mother'=>$name_mother,
							 'name_father'=>$name_father,
							 'date_update'=>"".date('Y-m-d H:i:s').""));
					if ($valid_image){
						# Compose the new filename
						$photo_filename=$pid.'.'.$picext;
						# Save the file
						$img_obj->saveUploadedImage($_FILES['photo_filename'],$root_path.$photo_path.'/',$photo_filename);
				   		# add to the sql query
						//$sql.=" photo_filename='$photo_filename',";
                                                $values[1]['photo_filename']=$photo_filename;
					}

					# complete the sql query
					//$sql.=" history=".$person_obj->ConcatHistory("Update ".date('Y-m-d H:i:s')." ".$_SESSION['sess_user_name']." \n").", modify_id='".$_SESSION['sess_user_name']."' WHERE pid=$pid";
                                        $values[1]['history']="".$person_obj->ConcatHistory("Update ".date('Y-m-d H:i:s')." ".$_SESSION['sess_user_name']." \n")."";
                                        $values[1]['modify_id']="".$_SESSION['sess_user_name']."";
                                        $values[0]['pid']=$pid;
                                        $ok=$db->Transact($values[0],$values[1],"Update",$dbtable);
                                        //var_dump($ok);
                                        //var_dump($values);


					//$db->debug=true;
					//echo $sql;
                                        //var_dump($sql);
					//$db->BeginTrans();
					//$ok=$db->Execute($sql);
					if($ok) {
						//$db->CommitTrans();
						# Update the insurance data
						# Lets detect if the data is already existing
						if($insurance_show) {
							if($insurance_item_nr) {
								if(!empty($insurance_nr) && !empty($insurance_firm_name) && $insurance_firm_id) {

									$insure_data=array('insurance_nr'=>$insurance_nr,
											'firm_id'=>$insurance_firm_id,
											'class_nr'=>$insurance_class_nr,
											'history'=>"Update ".date('Y-m-d H:i:s')." ".$_SESSION['sess_user_name']." \n",
											'modify_id'=>$_SESSION['sess_user_name'],
											'modify_time'=>date('YmdHis')
											);

									$pinsure_obj->updateDataFromArray($insure_data,$insurance_item_nr);
								}
							} elseif ($insurance_nr && $insurance_firm_name  && $insurance_class_nr) {
								$insure_data=array('insurance_nr'=>$insurance_nr,
											'firm_id'=>$insurance_firm_id,
											'pid'=>$pid,
											'class_nr'=>$insurance_class_nr,
											'history'=>"Update ".date('Y-m-d H:i:s')." ".$_SESSION['sess_user_name']." \n",
											'create_id'=>$_SESSION['sess_user_name'],
											'create_time'=>date('YmdHis')
										);
								$pinsure_obj->insertDataFromArray($insure_data);
							}
						}
						$newdata=1;
						//$db->debug=1;
						// KB: save other_his_no
						if( isset($_POST['other_his_org']) && !empty($_POST['other_his_org'])){
							$person_obj->OtherHospNrSet($_POST['other_his_org'], $_POST['other_his_no'], $_SESSION['sess_user_name'] );
						}

						if(file_exists($this->displayfile)){
                                                        
							header("Location: $this->displayfile".URL_REDIRECT_APPEND."&pid=$pid&from=$from&newdata=1&target=entry");
							exit;
						}else{
							echo $LDFileNo;
						}
					} else {
						echo "<p>error al modificar un paciente, puede que no tenga permisos<p>";
                                                ////$db->RollbackTrans();
					}







  				} else {

					$from='entry';
					$_POST['date_birth']=@formatDate2Std($date_birth,$date_format);
					$_POST['date_reg']=date('Y-m-d H:i:s');
					$_POST['blood_group']=trim($_POST['blood_group'].$_POST['rh']);
					$_POST['nat_id_nr']=trim($_POST['nat_id_nr_tipo'].$_POST['nat_id_nr']);
					$_POST['status']='normal';
					$_POST['history']="Init.reg. ".date('Y-m-d H:i:s')." ".$_SESSION['sess_user_name']."\n";
					//$_POST['modify_id']=$_SESSION['sess_user_name'];
					$_POST['create_id']=$_SESSION['sess_user_name'];
					$_POST['create_time']=date('YmdHis');

					# Prepare internal data to be stored together with the user input data
					if(!$person_obj->InitPIDExists($GLOBAL_CONFIG['person_id_nr_init'])){
						# If db is mysql, insert the initial pid value  from global config
						# else let the dbms make an initial value via the sequence generator e.g. postgres
						# However, the sequence generator must be configured during db creation to start at
						# the initial value set in the global config
						if($dbtype=='mysql'){
							$_POST['pid']=$GLOBAL_CONFIG['person_id_nr_init'];
						}
					}else{
						# Persons are existing. Check if duplicate might exist
						if(is_object($duperson=$person_obj->PIDbyData($_POST))){
							$error_person_exists=TRUE;
						}
					}
					//echo $person_obj->getLastQuery();

					if(!$error_person_exists||$mode=='forcesave'){
						if($person_obj->insertDataFromInternalArray()){
							
							# If data was newly inserted, get the insert id if mysql, 
							# else get the pid number from the latest primary key
							
							if(!$update){
								$oid = $db->Insert_ID();
								$pid=$person_obj->LastInsertPK('pid',$oid);
								//EL: set the new pid
								$person_obj->setPID($pid);
							}

							// KB: save other_his_no
							if( isset($_POST['other_his_org']) && !empty($_POST['other_his_org'])){
								$person_obj->OtherHospNrSet($_POST['other_his_org'], $_POST['other_his_no'], $_SESSION['sess_user_name'] );
							}
							
							# Save the valid uploaded photo
							if($valid_image){
								# Compose the new filename by joining the pid number and the file extension with "."
								$photo_filename=$pid.'.'.$picext;
								# Save the file
								if($img_obj->saveUploadedImage($_FILES['photo_filename'],$root_path.$photo_path.'/',$photo_filename)){
									# Update the filename to the databank
									$person_obj->setPhotoFilename($pid,$photo_filename);
								}
							}

							//echo $pid;
							# Update the insurance data
							# Lets detect if the data is already existing
							if($insurance_show) {
				  				if($insurance_item_nr) {
									if(!empty($insurance_nr) && !empty($insurance_firm_name) && $insurance_firm_id) {
										$insure_data=array('insurance_nr'=>$insurance_nr,
													'firm_id'=>$insurance_firm_id,
													'class_nr'=>$insurance_class_nr);
										$pinsure_obj->updateDataFromArray($insure_data,$insurance_item_nr);
									}
								} elseif ($insurance_nr && $insurance_firm_name  && $insurance_class_nr) {
									$insure_data=array('insurance_nr'=>$insurance_nr,
													'firm_id'=>$insurance_firm_id,
													'pid'=>$pid,
													'class_nr'=>$insurance_class_nr);
									$pinsure_obj->insertDataFromArray($insure_data);
								}
							}
							$newdata=1;
							if(file_exists($this->displayfile)){
								header("Location: $this->displayfile".URL_REDIRECT_APPEND."&pid=$pid&from=$from&newdata=1&target=entry");
								exit;
							}else{
								echo $LDFileNo;
							}
						}else {
							echo "<p>error al crear un nuevo paciente, puede que no tenga permisos<p>";
						}
					}
				}
			} // end of if(!$error)
		}elseif(!empty($this->pid)){
			 # Get the person�s data
			if($data_obj=&$person_obj->getAllInfoObject()){

				$zeile=$data_obj[0];
				extract($zeile);
			
				$rh = substr($blood_group, strlen($blood_group) - 1);
				$blood_group = substr($blood_group, 0, strlen($blood_group) - strlen($rh));

				$cedula_tipo = substr($nat_id_nr, 0, 1);
				$cedula_numero = substr($nat_id_nr, 1);

                                # Get the related insurance data
				$p_insurance=&$pinsure_obj->getPersonInsuranceObject($pid);
				if($p_insurance==FALSE) {
					$insurance_show=TRUE;
				} else {
					if(!$p_insurance->RecordCount()) {
						$insurance_show=TRUE;
					} elseif ($p_insurance->RecordCount()==1){
						$buffer= $p_insurance->FetchRow();
						extract($buffer);
						$insurance_show=TRUE;
						$insurance_firm_name=$pinsure_obj->getFirmName($insurance_firm_id);
					} else {
						$insurance_show=FALSE;
					}
				}
			}
		} else {
			$date_reg=date('Y-m-d H:i:s');
		}
		# Get the insurance classes
		$insurance_classes=&$pinsure_obj->getInsuranceClassInfoObject('class_nr,name,LD_var AS "LD_var"');

		include_once($root_path.'include/inc_photo_filename_resolve.php');
		
		#
		#
		########  Here starts the GUI output #######################################################
		#
		#
		
		# Start Smarty templating here
		# Create smarty object without initiliazing the GUI (2nd param = FALSE)

		include_once($root_path.'gui/smarty_template/smarty_care.class.php');
		$this->smarty = new smarty_care('common',FALSE);

		$img_male=createComIcon($root_path,'spm.gif','0');
		$img_female=createComIcon($root_path,'spf.gif','0');

		if(!empty($this->pretext)) $this->smarty->assign('pretext',$this->pretext);

		# Collect extay javascript code
		$sTemp='';
		ob_start();
?>
	<script  language="javascript">

                var http_request = false;
                function makePOSTRequest(url) { 
                    parameters="val=" + document.getElementById('nat_id_nr').value;
                    http_request = false;
                    if (window.XMLHttpRequest) { // Mozilla, Safari,...
                        http_request = new XMLHttpRequest();
                        if (http_request.overrideMimeType) {
                                // set type accordingly to anticipated content type
                            //http_request.overrideMimeType('text/xml');
                            http_request.overrideMimeType('text/html');
                        }
                    } else if (window.ActiveXObject) { // IE
                        try {
                            http_request = new ActiveXObject("Msxml2.XMLHTTP");
                        } catch (e) {
                            try {
                            http_request = new ActiveXObject("Microsoft.XMLHTTP");
                            } catch (e) {}
                        }
                    }
                    if (!http_request) {
                        alert('Cannot create XMLHTTP instance');
                        return false;
                    }

                    http_request.onreadystatechange = alertContents;
                    http_request.open('POST', url, true);
                    http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                    http_request.setRequestHeader("Content-length", parameters.length);
                    http_request.setRequestHeader("Connection", "close");
                    http_request.send(parameters);
                }

                function alertContents() {
                    if (http_request.readyState == 4) {
                        if (http_request.status == 200) {
                            eval(http_request.responseText); 
                        } else {
                            alert('There was a problem with the request.' + http_request.status);
                        }
                    }
                }

		var dtCh= "/";
		var minYear=1900;
		var maxYear=2100;

		function forceSave(){
			document.aufnahmeform.mode.value="forcesave";
			document.aufnahmeform.submit();
		}

		function showpic(d){
			if(d.value) document.images.headpic.src=d.value;
			if(d.value) document.images.headpic.src=d.value;
		}

		function popSearchWin(target,obj_val,obj_name){
			urlholder="./data_search.php<?php echo URL_REDIRECT_APPEND; ?>&target="+target+"&obj_val="+obj_val+"&obj_name="+obj_name;
			DSWIN<?php echo $sid ?>=window.open(urlholder,"wblabel<?php echo $sid ?>","menubar=no,width=400,height=550,resizable=yes,scrollbars=yes");
		}

		function chkform(d) {
			//Verificacion de solo numeros en el telefono celular 
			if(d.cellphone_1_nr_cod.value != ""){
				var strValue = d.cellphone_1_nr_cod.value;
				var fValue = parseFloat( strValue );
				
				if ( isNaN( fValue ) )
				{
					d.cellphone_1_nr_cod.focus();
					alert("<?php echo $LDTlfCodNo; ?>");
					return false;
				}
			}
			if(d.cellphone_1_nr.value != ""){
				var strValue = d.cellphone_1_nr.value;
				var fValue = parseFloat( strValue );
				
				if ( isNaN( fValue ) )
				{
					d.cellphone_1_nr.focus();
					alert("<?php echo $LDTlf; ?>");
					return false;
				}
			}
	
			//Verificacion de solo numeros en el telefono
			if(d.phone_1_nr_cod.value != ""){
				var strValue = d.phone_1_nr_cod.value;
				var fValue = parseFloat( strValue );
				
				if ( isNaN( fValue ) )
				{
					d.phone_1_nr_cod.focus();
					alert("<?php echo $LDTlfCodNo; ?>"); 
					return false;
				}
			}
			if(d.phone_1_nr.value != ""){
				var strValue = d.phone_1_nr.value;
				var fValue = parseFloat( strValue );
				
				if ( isNaN( fValue ) )
				{
					d.phone_1_nr.focus();
					alert("<?php echo $LDTlf; ?>"); 
					return false;
				}
			}
	
			//Verificacion de solo numeros en el zipcode
			if(d.addr_zip.value != ""){
				var strValue = d.addr_zip.value;
				var fValue = parseFloat( strValue );
				
				if ( isNaN( fValue ) )
				{
					d.addr_zip.focus();
					alert("<?php echo $LDCodigoPostNo; ?>"); 
					return false;
				}
			}
	
			//Verificaciones de solo numeros en el anios aprobados
			if(d.years_approved.value != ""){
				var strValue = d.years_approved.value;
				var fValue = parseFloat( strValue );
				
				if ( isNaN( fValue ) )
				{
					d.years_approved.focus();
					alert("<?php echo $LDAnosAprobNo; ?>");
					return false;
				}
			}

			//Verificaciones de solo numeros en el tiempo de residencia
			if(d.addr_time.value != ""){
				var strValue = d.addr_time.value;
				var fValue = parseFloat( strValue );
				
				if ( isNaN( fValue ) )
				{
					d.addr_time.focus();
					alert("<?php echo $LDResiNo; ?>");
					return false;
				}
			}
	
			//Verificacion de correo electronico
			if(d.email.value!=""){
				if (!isMail(d.email.value)) {
					alert("<?php echo $LDCorreoNo; ?>");
					d.email.focus();
					return false;
				}
			}

			/*if(d.nat_id_nr.value!=""){ // Cedula de Identidad

				if (((d.nat_id_nr.value).charAt(0)!='V') && ((d.nat_id_nr.value).charAt(0)!='v') && ((d.nat_id_nr.value).charAt(0)!='E') && ((d.nat_id_nr.value).charAt(0)!='e')){
					alert("El numero de cedula debe comenzar con V o E, ejemplo: V12345678");
					return false;
				}
				}*/

			if(d.name_last.value==""){
				alert("<?php echo $LDPlsEnterLastName; ?>");
				d.name_last.focus();
				return false;
			}else if(d.name_first.value==""){
				alert("<?php echo $LDPlsEnterFirstName; ?>");
				d.name_first.focus();
				return false;
			}else if(d.nat_id_nr.value==""){ // Cedula de Identidad
			  if (d.nat_id_nr_tipo.value != "N") {
				alert("<?php echo $LDPlsEnterNatIdNr; ?>");
				d.nat_id_nr.focus();
				return false;
			  }
			}else if(d.citizenship.value==""){//
				alert("<?php echo $LDPlsEnterCitizenship; ?>");
				d.citizenship.focus();
				return false;
			}else if(d.date_birth.value==""){
				alert("<?php echo $LDPlsEnterDateBirth; ?>");
				d.date_birth.focus();
				return false;

			}else if(d.sex=="") {
				alert("<?php echo $LDPlsSelectSex; ?>");
				return false;
			}else if(d.civil_status==""){//
				alert("<?php echo $LDPlsSelectCivilStatus; ?>");
				return false;
			}else if(d.educational_level==""){//
				alert("<?php echo $LDPlsSelectEducationalLevel; ?>");
				return false;
			}else if(d.educational_plan==""){//
				alert("<?php echo $LDPlsSelectEducationalPlan; ?>");
				return false;
			}else if(d.sso==""){//
				alert("<?php echo $LDPlsSelectSso; ?>");
				return false;
			}else if(d.addr_entity.value==""){//
				alert("<?php echo $LDPlsEnterStreetEntity; ?>");
				d.addr_entity.focus();
				return false;
			}else if(d.addr_town.value==""){//
				alert("<?php echo $LDPlsEnterAddrTown; ?>");
				d.addr_town.focus();
				return false;
			}else if(d.addr_citytown_name.value==""){//
				alert("<?php echo $LDPlsEnterCitytownName; ?>");
				d.addr_citytown_name.focus();
				return false;
			}else if(d.addr_locality.value==""){//
			  alert("<?php echo $LDPlsEnterAddrLocality; ?>");
			  d.addr_locality.focus();
			  return false;
			  
			}else if(d.addr_sector.value==""){//
			  alert("<?php echo $LDPlsEnterAddrSector; ?>");
			  d.addr_locality.focus();
			  return false;
			}
	
			return true;
		}

		function setNacionalidad() {
		  if (document.aufnahmeform.nat_id_nr_tipo.value == 'V') {

		    document.aufnahmeform.citizenship.value = 'VENEZOLANO';
		    document.aufnahmeform.nat_id_nr.disabled = false;

		  } else if (document.aufnahmeform.nat_id_nr_tipo.value == 'E') {

		    if (document.aufnahmeform.citizenship.value == 'VENEZOLANO') {
		      document.aufnahmeform.citizenship.value = '';
		    }
		    document.aufnahmeform.nat_id_nr.disabled = false;

		  } /*else if (document.aufnahmeform.nat_id_nr_tipo.value == 'N') {

		    document.aufnahmeform.nat_id_nr.value = '';
		    document.aufnahmeform.nat_id_nr.disabled = false;

		    }*/
		  return true;
		}

                

		function isMail(Cadena) {
			Punto = Cadena.substring(Cadena.lastIndexOf('.') + 1, Cadena.length);         //Cadena del .com  
			Dominio = Cadena.substring(Cadena.lastIndexOf('@') + 1, Cadena.lastIndexOf('.'));    // Dominio @lala.com  
			Usuario = Cadena.substring(0, Cadena.lastIndexOf('@'));                  // Cadena lalala@  
			Reserv = "@â„Âº\"\'+*{}\\<>?Â¿[]Ã¡Ã©Ã­Ã³Ãº#Â·Â¡!^*;,:";                      	// Letras Reservadas  
			valido = true;
		
			//verifica que el Usuario no tenga un caracter especial  
			for (var Cont=0; Cont<Usuario.length; Cont++) {
				X = Usuario.substring(Cont,Cont+1);
				if (Reserv.indexOf(X)!=-1)
					valido = false;
			}  
	
			//verifica qie el Punto no tenga un caracter especial  
			for (var Cont=0; Cont<Punto.length; Cont++) {  
				X=Punto.substring(Cont,Cont+1);
				if (Reserv.indexOf(X)!=-1)  
					valido = false;
				}
		
			//verifica qie el Dominio no tenga un caracter especial  
			for (var Cont=0; Cont<Dominio.length; Cont++) {  
				X=Dominio.substring(Cont,Cont+1);
				if (Reserv.indexOf(X)!=-1) 
					valido = false;
			}
	
			//Verifica la sintaxis bÃ¡sica.....  
			if (Punto.length<2 || Dominio <1 || Cadena.lastIndexOf('.')<0 || Cadena.lastIndexOf('@')<0 || Usuario<1) {  
				valido = false;
			}
		
			return valido;
		}



<?php
		require($root_path.'include/inc_checkdate_lang.php'); 
?>
		</script>
                <script language="javascript" src="<?php echo $root_path; ?>js/maxlength.js"></script>
<?php
		//gjergji : new calendar
		require_once ('../../js/jscalendar/calendar.php');
		$calendar = new DHTML_Calendar('../../js/jscalendar/', $lang, 'calendar-system', true);
		$calendar->load_files();
		//end : gjergji
		$sTemp = ob_get_contents();
		ob_end_clean();
		
		$this->smarty->assign('sRegFormJavaScript',$sTemp);

		$this->smarty->assign('thisfile',$thisfile);
                $this->smarty->assign('LDI',""/*$LDIgnr*/);

		if($error) {
			$this->smarty->assign('error',TRUE);
			$this->smarty->assign('sErrorImg','<img '.createMascot($root_path,'mascot1_r.gif','0','bottom').' align="absmiddle">');
			if ($error>1) $this->smarty->assign('sErrorText',$LDErrorS);
				else $this->smarty->assign('sErrorText',$LDError);
		
		}elseif($error_person_exists){
			$this->smarty->assign('errorDupPerson',TRUE);
			$this->smarty->assign('sErrorImg','<img '.createMascot($root_path,'mascot1_r.gif','0','bottom').' align="absmiddle">');
			$this->smarty->assign('LDPersonDuplicate',$LDPersonDuplicate);
			if($duperson->RecordCount()>1) $this->smarty->assign('sErrorText',"$LDSimilarData2 $LDPlsCheckFirst2");
				else $this->smarty->assign('sErrorText',"$LDSimilarData $LDPlsCheckFirst");

			$this->smarty->assign('sDupDataColNameRow',"<tr class=\"reg_div\">
					<td><font  size=-1  face=\"Arial\"><b>
						$LDRegistryNr</b>*</td>
					<td><font  size=-1  face=\"Arial\"><b>
						$LDLastName</b>*</td>
					<td><font  size=-1  face=\"Arial\"><b>
						$LDFirstName</b>*</td>
					<td><font  size=-1  face=\"Arial\"><b>
						$LDBday</b>*</td>
					<td><font  size=-1  face=\"Arial\"><b>
						$LDSex</b>*</td>
					<td><font  size=-1  face=\"Arial\"><b>
						$LDOptions</b>*</td>
					</tr>");

			# List and show the probable same person(s)

			$toggler=FALSE;
			$sTemp='';
			while($dup=$duperson->FetchRow()){
				if($toggler) $sRowClass='wardlistrow2';
					else $sRowClass='wardlistrow1';
				$toggler = !$toggler;
				$sTemp= $sTemp."\n".'
					<tr class="'.$sRowClass.'">
					<td>'.$dup['pid'].'</td>
					<td>'.$dup['name_last'].'</td>
					<td>'.$dup['name_first'].'</td>
					<td>'.formatDate2Local($dup['date_birth'],$date_format).'</td>
					<td>';
				switch($dup['sex']){
					case 'f': $sTemp = $sTemp.'<img '.$img_female.'>'; break;
					case 'm': $sTemp = $sTemp.'<img '.$img_male.'>'; break;
					default: $sTemp = $sTemp.'&nbsp;';
				}
				$sTemp = $sTemp.'
					</td>
					<td>:: <a href="person_reg_showdetail.php'.URL_APPEND.'&pid='.$dup['pid'].'&from=$from&newdata=1&target=entry" target="_blank">'.$LDShowDetails.'</a> ::
					<a href="patient_register.php'.URL_APPEND.'&pid='.$dup['pid'].'&update=1">'.$LDUpdate.'</a>
					</td>
					</tr>';
			}
			$this->smarty->assign('sDupDataRows',$sTemp);
		}
		
		if($pid) $this->smarty->assign('LDRegistryNr',$LDRegistryNr);
		$this->smarty->assign('pid',$pid);
		$this->smarty->assign('img_source',$img_source);
		$this->smarty->assign('LDPhoto',$LDPhoto);
		if(isset($photo_filename)) $pfile= $photo_filename;
			else $pfile='';
		$this->smarty->assign('sFileBrowserInput','<input name="photo_filename" type="file" size="15"   onChange="showpic(this)" value="'.$pfile.'">');
		
		# iRowSpanCount counts the rows on the left of the photo image. Begin with 5 because there are 5 static rows.
		$iRowSpanCount = 5;

		$this->smarty->assign('LDRegDate',$LDRegDate);
		$this->smarty->assign('sRegDate',formatDate2Local($date_reg,$date_format).'<input name="date_reg" type="hidden" value="'.$date_reg.'">');

		//$iRowSpanCount++;
		$this->smarty->assign('LDRegTime',$LDRegTime);
		$this->smarty->assign('sRegTime',convertTimeToLocal(formatDate2Local($date_reg,$date_format,0,1)));

		// Made hideable as suggested by Kurt brauchli
		if (!$GLOBAL_CONFIG['person_title_hide']){
			$this->smarty->assign('sPersonTitle',$this->createTR( $errortitle, 'title', $LDTitle, $title, '', 14 ));
			$iRowSpanCount++;
		}

		$this->smarty->assign('sNameLast',$this->createTR($errornamelast, 'name_last', $LDLastName,$name_last,'',35,TRUE));
		//$iRowSpanCount++;
		$this->smarty->assign('sNameFirst',$this->createTR($errornamefirst, 'name_first', $LDFirstName,$name_first,'',35,TRUE));
		//$iRowSpanCount++;
		if ($errorrelative) $this->smarty->assign('LDRelative',"<font color=red>$LDRelative</font>");
				else $this->smarty->assign('LDRelative',"$LDRelative");
		$this->smarty->assign('sRelativeNameLast',$this->createTR($errorrelativenamelast, 'relative_name_last', $LDLastName,$relative_name_last,2,35,FALSE));
			$this->smarty->assign('sRelativeNameFirst',$this->createTR($errorrelativenamefirst, 'relative_name_first', $LDFirstName,$relative_name_first,2,35,FALSE));
			$this->smarty->assign('sRelativePhone',$this->createTR($errorrelativephone, 'relative_phone', $LDPhone,$relative_phone,2,35,FALSE));


		if (!$GLOBAL_CONFIG['person_name_2_hide']){
			$this->smarty->assign('sName2',$this->createTR($errorname2, 'name_2', $LDName2,$name_2));
			$iRowSpanCount++;
		}

		if (!$GLOBAL_CONFIG['person_name_3_hide']){
			$this->smarty->assign('sName3',$this->createTR($errorname3, 'name_3', $LDName3,$name_3));
			$iRowSpanCount++;
		}

		if (!$GLOBAL_CONFIG['person_name_middle_hide']){
			$this->smarty->assign('sNameMiddle',$this->createTR($errornamemid, 'name_middle', $LDNameMid,$name_middle));
			$iRowSpanCount++;
		}

		if (!$GLOBAL_CONFIG['person_name_maiden_hide']){
			$this->smarty->assign('sNameMaiden',$this->createTR($errornamemaiden, 'name_maiden', $LDNameMaiden,$name_maiden));
			$iRowSpanCount++;
		}

		if (!$GLOBAL_CONFIG['person_name_others_hide']){
			$this->smarty->assign('sNameOthers',$this->createTR($errornameothers, 'name_others', $LDNameOthers,$name_others));
			$iRowSpanCount++;
		}

		# Set the rowspan value for the photo image <td>
		$this->smarty->assign('sPicTdRowSpan',"rowspan=$iRowSpanCount");


		if ($errordatebirth) $this->smarty->assign('LDBday',"<font color='#ff0000'>$LDBday</font>");
			else $this->smarty->assign('LDBday',"<font color='#ff0000'>$LDBday</font>");
			
		//gjergji : new calendar
		$this->smarty->assign('sBdayInput',$calendar->show_calendar($calendar,$date_format,'date_birth',$date_birth));
		//end gjergji
		//echo "$LDSex";
		if ($errorsex) $this->smarty->assign('LDSex', "<font color='#ff0000'>$LDSex</font>:");
			else $this->smarty->assign('LDSex', "<font color='#ff0000'>$LDSex</font>");

		$sSexMBuffer='<select name="sex"><option value="m" ' . (($sex == "m")?("selected"):("")) . '>' . $LDMale . '</option><option value="f" ' . (($sex == "f")?("selected"):("")) . '>' . $LDFemale . '</option></select>';
		$this->smarty->assign('sSexM',$sSexMBuffer);
		$this->smarty->assign('sSexF',""/*$sSexFBuffer*/);
		$this->smarty->assign('LDMale',""/*$LDMale*/);
		$this->smarty->assign('LDFemale',""/*$LDFemale*/);

		# But patch 2004-03-10
		# Clean blood group
		$blood_group = trim($blood_group);

		//  Made hideable as suggested by Kurt Brauchli
		if (!$GLOBAL_CONFIG['person_bloodgroup_hide'] ){
			$this->smarty->assign('LDBloodGroup',$LDBloodGroup);
                        $this->smarty->assign('LDRH',$LDRH);
			
			$sBGBuffer='<select name="blood_group">';
			$sBGBuffer.='<option value="A" ' . (($blood_group == 'A')?("selected"):("")) . '>' . $LDA . '</option>';
			$sBGBuffer.='<option value="B" ' . (($blood_group == 'B')?("selected"):("")) . '>' . $LDB . '</option>';
			$sBGBuffer.='<option value="AB" ' . (($blood_group == 'AB')?("selected"):("")) . '>' . $LDAB . '</option>';
			$sBGBuffer.='<option value="O" ' . (($blood_group == 'O')?("selected"):("")) . '>' . $LDO . '</option>';
			$sBGBuffer.='<option value="Ig" ' . (($blood_group == 'Ig' || $blood_group == '')?("selected"):("")) . '>' . $LDIgnr . '</option>';
			$sBGVuffer.='</select>';

			$this->smarty->assign('sBGAInput',$sBGBuffer);
			$this->smarty->assign('sBGBInput',""/*$sBGBuffer*/);
			$this->smarty->assign('sBGABInput',""/*$sBGBuffer*/);
			$this->smarty->assign('sBGOInput',""/*$sBGBuffer*/);
			$this->smarty->assign('sBGIInput',""/*$sBGBuffer*/);
			
			$this->smarty->assign('LDA',""/*$LDA*/);
			$this->smarty->assign('LDB',""/*$LDB*/);
			$this->smarty->assign('LDAB',""/*$LDAB*/);
			$this->smarty->assign('LDO',""/*$LDO*/);


			$sBGBuffer='<select name="rh">';
			$sBGBuffer.='<option value="+" ' . (($rh == '+')?("selected"):("")) . '>' . $LDPos . '</option>';
			$sBGBuffer.='<option value="-" ' . (($rh == '-')?("selected"):("")) . '>' . $LDNeg . '</option>';
			$sBGBuffer.='<option value="I" ' . (($rh == 'I' || $rh == '')?("selected"):("")) . '>' . $LDIgnr . '</option>';
			$sBGBuffer.='</select>';
                        
			$this->smarty->assign('sRHPInput',$sBGBuffer);
			$this->smarty->assign('sRHNInput',""/*$sBGBuffer*/);
			$this->smarty->assign('sRHIInput',""/*$sBGBuffer*/);
			$this->smarty->assign('LDP',""/*$LDPos*/);
			$this->smarty->assign('LDN',""/*$LDNeg*/);

		}
		// KB: make civil status hideable
		if (!$GLOBAL_CONFIG['person_civilstatus_hide']){
			$this->smarty->assign('LDCivilStatus','<font color="red">' . $LDCivilStatus . '</font>');
			
			$sCSBuffer = '<select name="civil_status">';
			$sCSBuffer.= '<option value="single" ' . (($civil_status == "single")?("selected"):("")) . '>' . $LDSingle . ' </option>';
			$sCSBuffer.= '<option value="married" ' . (($civil_status == "married")?("selected"):("")) . '>' . $LDMarried . ' </option>';
			$sCSBuffer.= '<option value="divorced" ' . (($civil_status == "divorced")?("selected"):("")) . '>' . $LDDivorced . ' </option>';
			$sCSBuffer.= '<option value="widowed" ' . (($civil_status == "widowed")?("selected"):("")) . '>' . $LDWidowed . ' </option>';
			$sCSBuffer.= '<option value="separated" ' . (($civil_status == "separated")?("selected"):("")) . '>' . $LDSeparated . ' </option>';
			$sCSBuffer.= '<option value="concubino" ' . (($civil_status == "concubino")?("selected"):("")) . '>' . $LDConcubino . ' </option>';
			$sCSBuffer.= '</select>';

			$this->smarty->assign('sCSSingleInput',$sCSBuffer);
			$this->smarty->assign('sCSMarriedInput',""/*$sCSBuffer.'>'*/);
			$this->smarty->assign('sCSDivorcedInput',""/*$sCSBuffer.'>'*/);
			$this->smarty->assign('sCSWidowedInput',""/*$sCSBuffer.'>'*/);
			$this->smarty->assign('sCSSeparatedInput',""/*$sCSBuffer.'>'*/);

			$this->smarty->assign('LDSingle',""/*$LDSingle*/);
			$this->smarty->assign('LDMarried',""/*$LDMarried*/);
			$this->smarty->assign('LDDivorced',""/*$LDDivorced*/);
			$this->smarty->assign('LDWidowed',""/*$LDWidowed*/);
			$this->smarty->assign('LDSeparated',""/*$LDSeparated*/);
		}
		
		if ($erroraddress) $this->smarty->assign('LDAddress',"<font color=red>$LDAddress</font>");
			else $this->smarty->assign('LDAddress',"$LDAddress");

		if ($errorstreet) $this->smarty->assign('LDStreet',"<font color=red><font color=#ff0000></font> $LDStreet</font>");
			else $this->smarty->assign('LDStreet',"<font color=#ff0000></font> $LDStreet");

		$this->smarty->assign('sStreetInput','<input name="addr_str" type="text" size="35" value="'.$addr_str.'">');

		if ($errorstreetnr) $this->smarty->assign('LDStreetNr',"<font color=red><font color=#ff0000></font> $LDStreetNr</font>");
				else $this->smarty->assign('LDStreetNr',"<font color=#ff0000></font> $LDStreetNr");

		$this->smarty->assign('sStreetNrInput','<input name="addr_str_nr" type="text" size="10" value="'.$addr_str_nr.'">');

		if ($errortown) $this->smarty->assign('LDStreet',"<font color=red>$LDTownCity</font>");
			else $this->smarty->assign('LDTownCity',"<font color=red>$LDTownCity</font>");
			$this->smarty->assign('sTownCityInput','<input name="addr_citytown_name" type="text" size="35" value="'.$addr_citytown_name.'">');
			$this->smarty->assign('sAddrCityTownMiniCalendar',"<a href=\"javascript:popSearchWin('addr_citytown_name',document.aufnahmeform.addr_entity_hide.value,document.aufnahmeform.addr_town_hide.value)\"><img ".createComIcon($root_path,'b-write_addr.gif','0')."></a>");

		 if ($errorzip) $this->smarty->assign('LDZipCode',"<font color=red><font color=#ff0000></font> $LDZipCode</font> ");
		 	else  $this->smarty->assign('LDZipCode',"<font color=#ff0000></font> $LDZipCode ");
		 $this->smarty->assign('sZipCodeInput','<input name="addr_zip" type="text" size="10" value="'.$addr_zip.'">');


		// KB: make insurance completely hideable
		if (!$GLOBAL_CONFIG['person_insurance_hide']){
			if($insurance_show) {
				if (!$person_insurance_1_nr_hide) {

					$this->smarty->assign('bShowInsurance',TRUE);

					$this->smarty->assign('sInsuranceNr',$this->createTR($errorinsurancenr, 'insurance_nr', $LDInsuranceNr.' 1',$insurance_nr,2));

					if ($errorinsuranceclass) $this->smarty->assign('sErrorInsClass',"<font color=\"$error_fontcolor\">");

					if($insurance_classes!=false){
						$sInsClassBuffer='';
						while($result=$insurance_classes->FetchRow()) {

							$sInsClassBuffer.='<input name="insurance_class_nr" type="radio"  value="'.$result['class_nr'].'" ';
							if($insurance_class_nr==$result['class_nr']) $sInsClassBuffer.='checked';
							$sInsClassBuffer.='>';

							$LD=$result['LD_var'];
							if(isset($$LD)&&!empty($$LD)) $sInsClassBuffer.=$$LD; else $sInsClassBuffer.=$result['name'];
							$sInsClassBuffer.='&nbsp;';
						}

						$this->smarty->append('sInsClasses',$sInsClassBuffer);

					} else {
						$this->smarty->assign('sInsClasses','no insurance class');
					}
					
					if ($errorinsurancecoid) $this->smarty->assign('LDInsuranceCo',"<font color=red>$LDInsuranceCo</font> :");
						else  $this->smarty->assign('LDInsuranceCo',"$LDInsuranceCo :");

					$this->smarty->assign('sInsCoNameInput','<input name="insurance_firm_name" type="text" size="35" value="'.$insurance_firm_name.'">');
					$this->smarty->assign('sInsCoMiniCalendar',"<a href=\"javascript:popSearchWin('insurance','aufnahmeform.insurance_firm_id','aufnahmeform.insurance_firm_name')\"><img ".createComIcon($root_path,'b-write_addr.gif','0')."></a>");
				}
			} else {
				$this->smarty->assign('bNoInsurance',TRUE);
				$this->smarty->assign('LDSeveralInsurances','<a href="#">$LDSeveralInsurances <img '.createComIcon($root_path,'frage.gif','0').'></a>');
			}
		}
		if (!$GLOBAL_CONFIG['person_phone_1_nr_hide']){
			$this->smarty->assign('sPhone1',$this->createTR($errorphone1, 'phone_1_nr', $LDPhone ,$phone_1_nr,2));
		}
		if (!$GLOBAL_CONFIG['person_phone_2_nr_hide']){
			$this->smarty->assign('sPhone2',$this->createTR($errorphone2, 'phone_2_nr', $LDPhone.' 2',$phone_2_nr,2));
		}
		if (!$GLOBAL_CONFIG['person_cellphone_1_nr_hide']){
			$this->smarty->assign('sCellPhone1',$this->createTR($errorcell1, 'cellphone_1_nr', $LDCellPhone,$cellphone_1_nr,2));
		}
		if (!$GLOBAL_CONFIG['person_cellphone_2_nr_hide']){
			$this->smarty->assign('sCellPhone2',$this->createTR($errorcell2, 'cellphone_2_nr', $LDCellPhone.' 2',$cellphone_2_nr,2));
		}
		if (!$GLOBAL_CONFIG['person_fax_hide']){
			$this->smarty->assign('sFax',$this->createTR($errorfax, 'fax', $LDFax,$fax,2));
		}
		if (!$GLOBAL_CONFIG['person_email_hide']){
			$this->smarty->assign('sEmail',$this->createTR($erroremail, 'email', $LDEmail,$email,2));
		}
		if (!$GLOBAL_CONFIG['person_citizenship_hide']){
			$this->smarty->assign('sCitizenship',$this->createTR($errorcitizen, 'citizenship', '<font color="red">' . $LDCitizenship . '</font>',$citizenship,2));
		}
		if (!$GLOBAL_CONFIG['person_sss_nr_hide']){
			$this->smarty->assign('sSSSNr',$this->createTR($errorsss, 'sss_nr', $LDSSSNr,$sss_nr,2));
		}
		if (!$GLOBAL_CONFIG['person_nat_id_nr_hide']){
		  $this->smarty->assign('sNatIdNr',$this->createTR($errornatid, 'nat_id_nr', '<font color="red">' .$LDNatIdNr . '</font>',$nat_id_nr,2, 15));
		}
		if (!$GLOBAL_CONFIG['person_religion_hide']){
			$this->smarty->assign('sReligion',$this->createTR($errorreligion, 'religion', $LDReligion,$religion,2));
		}
		if (!$GLOBAL_CONFIG['person_ethnic_orig_hide']){
                        $interconsulta = new Interconsulta;
                        $etnias = $interconsulta->loadEtnias();
                        $combo = '<select name="ethnic_orig"><option value="0">'.$LDSeleccione.'</option>';
                        if (count($etnias))
                        {
                            foreach ($etnias as $temp)
                            {
                                $combo .= '<option value="'. $temp["nr"] .'">' . $temp["name"] . '</option>';
                            }
                        }
                        $combo .= '</select>';
			/** Add by Jean-Philippe LIOT 13/05/2004 **/
			$this->smarty->assign('LDEthnicOrig',$LDEthnicOrigin);
			$this->smarty->assign('sEthnicOrigInput',$combo);
		}
		// KB: add a field for other HIS nr
		if (!$GLOBAL_CONFIG['person_other_his_nr_hide']){
			$this->smarty->assign('bShowOtherHospNr',TRUE);

			$this->smarty->assign('LDOtherHospitalNr',$LDOtherHospitalNr);

			$other_hosp_list = $person_obj->OtherHospNrList();
			$sOtherNrBuffer='';
			foreach( $other_hosp_list as $k=>$v ){
				$sOtherNrBuffer.="<b>".$kb_other_his_array[$k].":</b> ".$v."<br />\n";
			}

			$this->smarty->assign('sOtherNr',$sOtherNrBuffer);
			
			$sOtherNrBuffer='';
			$sOtherNrBuffer.="<SELECT name=\"other_his_org\">".
						"<OPTION value=\"\">--</OPTION>";
			foreach( $kb_other_his_array as $k=>$v ){
				$sOtherNrBuffer.="<OPTION value=\"$k\" $check>$v</OPTION>";
			}
			$sOtherNrBuffer.="</SELECT>\n".
					"&nbsp;&nbsp;".
					"$LDNr:<INPUT name=\"other_his_no\" size=20><br />\n";

			$sOtherNrBuffer.="($LDSelectOtherHospital - $LDNoNrNoDelete)".
						"<br />\n";
			$sOtherNrBuffer.="</TD></TR>\n\n";

			$this->smarty->assign('sOtherNrSelect',$sOtherNrBuffer);
		}

		if (!$GLOBAL_CONFIG['person_diagnosis_hide']){
			$this->smarty->assign('LDDiagnosis',$LDDiagnosis);
			$this->smarty->assign('sDiagnosisInput','<textarea name="diagnosis" cols="40" rows="15" wrap="virtual" style="overflow:auto;">'.$diagnosis.'</textarea>');
		}

		if (!$GLOBAL_CONFIG['person_birth_country_hide']){
			$this->smarty->assign('LDBirthCountry',$LDBirthCountry);
			$this->smarty->assign('sBirthCountryInput','<input name="birth_country" type="text" size="35" value="'.$birth_country.'" >');
		}

		if (!$GLOBAL_CONFIG['person_birth_entity_hide']){
			$this->smarty->assign('LDBirthEntity',$LDBirthEntity);
			$this->smarty->assign('sBirthEntityInput','<input name="birth_entity" type="text" size="35" value="'.$birth_entity.'" >');
			$this->smarty->assign('sBirthEntityMiniCalendar',"<a href=\"javascript:popSearchWin('birth_entity')\"><img ".createComIcon($root_path,'b-write_addr.gif','0')."></a>");

		}

		if (!$GLOBAL_CONFIG['person_birth_town_hide']){
			$this->smarty->assign('LDBirthTown',$LDBirthTown);
			$this->smarty->assign('sBirthTownInput','<input name="birth_town" type="text" size="35" value="'.$birth_town.'" >');
			$this->smarty->assign('sBirthTownMiniCalendar',"<a href=\"javascript:popSearchWin('birth_town',document.aufnahmeform.birth_entity_hide.value)\"><img ".createComIcon($root_path,'b-write_addr.gif','0')."></a>");

		}

		if (!$GLOBAL_CONFIG['person_birth_city_hide']){
			$this->smarty->assign('LDBirthCity',$LDBirthCity);
			$this->smarty->assign('sBirthCityInput','<input name="birth_city" type="text" size="35" value="'.$birth_city.'" >');
			$this->smarty->assign('sBirthCityMiniCalendar',"<a href=\"javascript:popSearchWin('birth_city',document.aufnahmeform.birth_entity_hide.value,document.aufnahmeform.birth_town_hide.value)\"><img ".createComIcon($root_path,'b-write_addr.gif','0')."></a>");
		}

		if (!$GLOBAL_CONFIG['person_illiterate_hide']){
			$this->smarty->assign('LDIlliterate',$LDIlliterate);
						
			$sCSBuffer = '<select name="illiterate">';
			$sCSBuffer.= '<option value="SI" ' . (($illiterate == "SI")?("selected"):("")) . '>' . $LDYes . ' </option>';
			$sCSBuffer.= '<option value="NO" ' . (($illiterate == "NO")?("selected"):("")) . '>' . $LDNo . ' </option>';
			$sCSBuffer.= '<option value="Ig" ' . (($illiterate == "Ig" || $illiterate == "")?("selected"):("")) . '>' . $LDIgnr . ' </option>';
			$sCSBuffer.= '</select>';

			$this->smarty->assign('sSiInput',$sCSBuffer);
			$this->smarty->assign('sNoInput',""/*$sCSBuffer.'>'*/);
			$this->smarty->assign('sIInput',""/*$sCSBuffer.'>'*/);

			$this->smarty->assign('LDYes',""/*$LDSingle*/);
			$this->smarty->assign('LDNo',""/*$LDMarried*/);
			
		}

		if (!$GLOBAL_CONFIG['person_educational_level_hide']){
			$this->smarty->assign('LDEducationalLevel',$LDEducationalLevel);

			$sCSBuffer = '<select name="educational_level">';
			$sCSBuffer.= '<option value="1" ' . (($educational_level == "1")?("selected"):("")) . '>' . $LDEducationalLevel1 . ' </option>';
			$sCSBuffer.= '<option value="2" ' . (($educational_level == "2")?("selected"):("")) . '>' . $LDEducationalLevel2 . ' </option>';
			$sCSBuffer.= '<option value="3" ' . (($educational_level == "3")?("selected"):("")) . '>' . $LDEducationalLevel3 . ' </option>';
			$sCSBuffer.= '<option value="4" ' . (($educational_level == "4")?("selected"):("")) . '>' . $LDEducationalLevel4 . ' </option>';
			$sCSBuffer.= '<option value="5" ' . (($educational_level == "5")?("selected"):("")) . '>' . $LDEducationalLevel5 . ' </option>';
			$sCSBuffer.= '<option value="6" ' . (($educational_level == "6")?("selected"):("")) . '>' . $LDEducationalLevel6 . ' </option>';
			$sCSBuffer.= '<option value="Ig" ' . (($educational_level == "Ig" || $educational_level == "")?("selected"):("")) . '>' . $LDIgnr . ' </option>';
			$sCSBuffer.= '</select>';

			$this->smarty->assign('sEducationalLevel1Input',$sCSBuffer);
			$this->smarty->assign('sEducationalLevel2Input',""/*$sCSBuffer*/);
			$this->smarty->assign('sEducationalLevel3Input',""/*$sCSBuffer*/);
			$this->smarty->assign('sEducationalLevel4Input',""/*$sCSBuffer*/);
			$this->smarty->assign('sEducationalLevel5Input',""/*$sCSBuffer*/);
			$this->smarty->assign('sEducationalLevel6Input',""/*$sCSBuffer*/);
			$this->smarty->assign('sEducationalLevelIInput',""/*$sCSBuffer*/);
			$this->smarty->assign('sIInput',""/*$sCSBuffer.'>'*/);

			$this->smarty->assign('LDEducationalLevel1',""/*$LDEducationalLevel1*/);
			$this->smarty->assign('LDEducationalLevel2',""/*$LDEducationalLevel2*/);
			$this->smarty->assign('LDEducationalLevel3',""/*$LDEducationalLevel3*/);
			$this->smarty->assign('LDEducationalLevel4',""/*$LDEducationalLevel4*/);
			$this->smarty->assign('LDEducationalLevel5',""/*$LDEducationalLevel5*/);
			$this->smarty->assign('LDEducationalLevel6',""/*$LDEducationalLevel6*/);
		}

		if (!$GLOBAL_CONFIG['person_educational_plan_hide']){
			$this->smarty->assign('LDEducationalPlan',$LDEducationalPlan);

			$sCSBuffer = '<select name="educational_plan">';
			$sCSBuffer.= '<option value="1" ' . (($educational_plan == "1")?("selected"):("")) . '>' . $LDEducationalPlan1 . ' </option>';
			$sCSBuffer.= '<option value="2" ' . (($educational_plan == "2")?("selected"):("")) . '>' . $LDEducationalPlan2 . ' </option>';
			$sCSBuffer.= '<option value="3" ' . (($educational_plan == "3")?("selected"):("")) . '>' . $LDEducationalPlan3 . ' </option>';
			$sCSBuffer.= '<option value="Ig" ' . (($educational_plan == "Ig" || $educational_plan == "")?("selected"):("")) . '>' . $LDIgnr . ' </option>';
			$sCSBuffer.= '</select>';

			$this->smarty->assign('sEducationalPlan1Input',$sCSBuffer);
			$this->smarty->assign('sEducationalPlan2Input',""/*$sCSBuffer*/);
			$this->smarty->assign('sEducationalPlan3Input',""/*$sCSBuffer*/);
			$this->smarty->assign('sEducationalLevelIInput',""/*$sCSBuffer*/);
			$this->smarty->assign('sIInput',""/*$sCSBuffer.'>'*/);

			$this->smarty->assign('LDEducationalPlan1',""/*$LDEducationalPlan1*/);
			$this->smarty->assign('LDEducationalPlan2',""/*$LDEducationalPlan2*/);
			$this->smarty->assign('LDEducationalPlan3',""/*$LDEducationalPlan3*/);

		}

		if (!$GLOBAL_CONFIG['person_years_approved_hide']){
			$this->smarty->assign('LDYearsApproved',$LDYearsApproved);
			$this->smarty->assign('sYearsApprovedInput','<input name="years_approved" type="text" size="35" value="'.$years_approved.'" >');
		}

		if (!$GLOBAL_CONFIG['person_profession_hide']){
			$this->smarty->assign('LDProfession',$LDProfession);
			$this->smarty->assign('sProfessionInput','<input name="profession" type="text" size="35" value="'.$profession.'" >');
		}

		if (!$GLOBAL_CONFIG['person_occupation_hide']){
			$this->smarty->assign('LDOccupation',$LDOccupation);
			$this->smarty->assign('sOccupationInput','<input name="occupation" type="text" size="35" value="'.$occupation.'" >');
		}

		if (!$GLOBAL_CONFIG['person_sso_hide']){
			$this->smarty->assign('LDSso','<font color="red">' . $LDSso . '</font>');
			
			$sCSBuffer = '<select name="sso">';
			$sCSBuffer.= '<option value="SI" ' . (($sso == "SI")?("selected"):("")) . '>' . $LDYes . ' </option>';
			$sCSBuffer.= '<option value="NO" ' . (($sso == "NO")?("selected"):("")) . '>' . $LDNo . ' </option>';
			$sCSBuffer.= '<option value="Ig" ' . (($sso == "Ig" || $sso == "")?("selected"):("")) . '>' . $LDIgnr . ' </option>';
			$sCSBuffer.= '</select>';

			$this->smarty->assign('sSSOSiInput',$sCSBuffer);
			$this->smarty->assign('sSSONoInput',""/*$sCSBuffer.'>'*/);
			$this->smarty->assign('sSSOIInput',""/*$sCSBuffer.'>'*/);

			$this->smarty->assign('LDSSOYes',""/*$LDSingle*/);
			$this->smarty->assign('LDSSONo',""/*$LDMarried*/);
		}

		if (!$GLOBAL_CONFIG['person_addr_entity_hide']){
			$this->smarty->assign('LDAddrEntity','<font color="red">' . $LDAddrEntity . '</font>');
			$this->smarty->assign('sAddrEntityInput','<input name="addr_entity" type="text" size="35" value="'.$addr_entity.'" >');
			$this->smarty->assign('sAddrEntityMiniCalendar',"<a href=\"javascript:popSearchWin('addr_entity')\"><img ".createComIcon($root_path,'b-write_addr.gif','0')."></a>");

		}

		if (!$GLOBAL_CONFIG['person_addr_locality_hide']){
			$this->smarty->assign('LDAddrLocality','<font color="red">' . $LDAddrLocality . '</font>');
			$this->smarty->assign('sAddrLocalityInput','<input name="addr_locality" type="text" size="35" value="'.$addr_locality.'" >');
		}

		if (!$GLOBAL_CONFIG['person_addr_sector_hide']){
			$this->smarty->assign('LDAddrSector','<font color="red">' . $LDAddrSector . '</font>');
			$this->smarty->assign('sAddrSectorInput','<input name="addr_sector" type="text" size="35" value="'.$addr_sector.'" >');
			$this->smarty->assign('sAddrSectorMiniCalendar',"<a href=\"javascript:popSearchWin('addr_sector', document.aufnahmeform.addr_entity.value)\"><img ".createComIcon($root_path,'b-write_addr.gif','0')."></a>");
		}


		if (!$GLOBAL_CONFIG['person_addr_town_hide']){
			$this->smarty->assign('LDAddrTown','<font color="red">' . $LDAddrTown . '</font>');
			$this->smarty->assign('sAddrTownInput','<input name="addr_town" type="text" size="35" value="'.$addr_town.'" >');
			$this->smarty->assign('sAddrTownMiniCalendar',"<a href=\"javascript:popSearchWin('addr_town',document.aufnahmeform.addr_entity_hide.value)\"><img ".createComIcon($root_path,'b-write_addr.gif','0')."></a>");

		}

		if (!$GLOBAL_CONFIG['person_addr_house_hide']){
			$this->smarty->assign('LDAddrHouse',$LDAddrHouse);
			$this->smarty->assign('sAddrHouseInput','<input name="addr_house" type="text" size="35" value="'.$addr_house.'" >');
		}

		if (!$GLOBAL_CONFIG['person_addr_floor_hide']){
			$this->smarty->assign('LDAddrFloor',$LDAddrFloor);
			$this->smarty->assign('sAddrFloorInput','<input name="addr_floor" type="text" size="35" value="'.$addr_floor.'" >');
		}

		if (!$GLOBAL_CONFIG['person_addr_reference_hide']){
			$this->smarty->assign('LDAddrReference',$LDAddrReference);
			$this->smarty->assign('sAddrReferenceInput','<input name="addr_reference" type="text" size="35" value="'.$addr_reference.'" >');
		}

		if (!$GLOBAL_CONFIG['person_addr_time_hide']){
			$this->smarty->assign('LDAddrTime',$LDAddrTime);
			$this->smarty->assign('sAddrTimeInput','<input name="addr_time" type="text" size="35" value="'.$addr_time.'" >');
		}

		if (!$GLOBAL_CONFIG['person_name_mother_hide']){
			$this->smarty->assign('LDNameMother',$LDNameMother);
			$this->smarty->assign('sNameMotherInput','<input name="name_mother" type="text" size="35" value="'.$name_mother.'" >');
		}

		if (!$GLOBAL_CONFIG['person_name_father_hide']){
			$this->smarty->assign('LDNameFather',$LDNameFather);
			$this->smarty->assign('sNameFatherInput','<input name="name_father" type="text" size="35" value="'.$name_father.'" >');
		}

		if (!$GLOBAL_CONFIG['CentroSalud_hide']){
			$this->smarty->assign('CentroSalud',$CentroSalud);
			$sCSBuffer = '<select name="CentroS">';
			$sCSBuffer.= '<option value="CentroS" ' . (($CentroS == "CentroS")?("selected"):("")) . '>' .$LDCentroSalud. ' </option>';
			$sCSBuffer.= '</select>';
			$this->smarty->assign('CentroSInput',$sCSBuffer);
		}		
		
		if (!$GLOBAL_CONFIG['person_comments_hide']){
			$this->smarty->assign('LDComments',$LDComments);
			$this->smarty->assign('sCommentsInput','<textarea name="comments" cols="43" rows="5" wrap="virtual" style="overflow:auto;">'.$comments.'</textarea>');

		}

		if (!$GLOBAL_CONFIG['person_imaging_hide']){
			$this->smarty->assign('LDImaging',$LDImaging);
			$this->smarty->assign('sImagingInput','<textarea name="imaging" cols="43" rows="5" wrap="virtual" style="overflow:auto;">'.$imaging.'</textarea>');
		}

		$this->smarty->assign('LDRegBy',$LDRegBy);
		if(isset($user_id) && $user_id) $buffer=$user_id; else  $buffer = $_SESSION['sess_user_name'];
		$this->smarty->assign('sRegByInput','<input  name="user_id" type="text" value="'.$buffer.'"  size="35" readonly>');

		# Collect the hidden inputs
		
		ob_start();
?>
			<INPUT TYPE="hidden" name="MAX_FILE_size" value="1000000">
			<input type="hidden" name="itemname" value="<?php echo $itemname; ?>">
			<input type="hidden" name="sid" value="<?php echo $sid; ?>">
			<input type="hidden" name="lang" value="<?php echo $lang; ?>">
			<input type="hidden" name="linecount" value="<?php echo $linecount; ?>">
			<input type="hidden" name="mode" value="save">
			<input type="hidden" name="addr_citytown_nr" value="<?php echo $addr_citytown_nr; ?>">
			<input type="hidden" name="insurance_item_nr" value="<?php echo $insurance_item_nr; ?>">
			<input type="hidden" name="insurance_firm_id" value="<?php echo $insurance_firm_id; ?>">
			<input type="hidden" name="insurance_show" value="<?php echo $insurance_show; ?>">
			<input type="hidden" name="birth_entity_hide" value="<?php echo $birth_entity_hide; ?>">
			<input type="hidden" name="birth_city_hide" value="<?php echo $birth_city_hide; ?>">
			<input type="hidden" name="birth_town_hide" value="<?php echo $birth_town_hide; ?>">
			<input type="hidden" name="addr_entity_hide" value="<?php echo $addr_entity_hide; ?>">
			<input type="hidden" name="addr_sector_hide" value="<?php echo $addr_sector_hide; ?>">
			<input type="hidden" name="addr_citytown_name_hide" value="<?php echo $addr_citytown_name_hide; ?>">
			<input type="hidden" name="addr_town_hide" value="<?php echo $addr_town_hide; ?>">
<?php
		if($update){
			$this->smarty->assign('sUpdateHiddenInputs','<input type="hidden" name="update" value=1><input type="hidden" name="pid" value="'.$pid.'">');
		}

		$sTemp= ob_get_contents();
		ob_end_clean();
		$this->smarty->assign('sHiddenInputs',$sTemp);

		$this->smarty->assign('pbSubmit','<input  type="image" '.createLDImgSrc($root_path,'savedisc.gif','0').'  alt="'.$LDSaveData.'" align="absmiddle">');
		$this->smarty->assign('pbReset','<a href="javascript:document.aufnahmeform.reset()"><img '.createLDImgSrc($root_path,'reset.gif','0').' alt="'.$LDResetData.'"   align="absmiddle"></a>');

		if($error||$error_person_exists) $this->smarty->assign('pbForceSave','<input  type="button" value="'.$LDForceSave.'" onClick="forceSave()">');

		if (!$newdata){
			ob_start();
?>
			<form action=<?php echo $thisfile; ?> method=post>
				<input type=hidden name=sid value=<?php echo $sid; ?>>
				<input type=hidden name=patnum value="">
				<input type=hidden name="lang" value="<?php echo $lang; ?>">
				<input type=hidden name="date_format" value="<?php echo $date_format; ?>">
				<input type=submit value="<?php echo $LDNewForm ?>" >
			</form>
<?php
			$sTemp= ob_get_contents();
			ob_end_clean();
			$this->smarty->assign('sNewDataForm',$sTemp);
		}

		# Set the form template as form
		$this->smarty->assign('bSetAsForm',TRUE);

		if($this->bReturnOnly){
			ob_start();
				$this->smarty->display('registration_admission/reg_form.tpl');
				$sTemp=ob_get_contents();
			ob_end_clean();
			return $sTemp;
		}else{
			# show Template
			$this->smarty->display('registration_admission/reg_form.tpl');
		}
	} // end of function

	function create(){
		$this->bReturnOnly = TRUE;
		return $this->display();
	}
} // end of class
?>
